﻿import { _decorator, Component, Node } from 'cc';
import { ComBase } from '../base/ComBase';
import { SysBase } from '../base/SysBase';
import { SysMgr } from '../common/SysMgr';
import { TimeSys } from './TimeSys';
import { Functor } from '../common/Functor';
import { WsCom } from '../net/WsCom';
import { GlobalVar } from '../common/GlobalVar';

import { Defines } from '../common/Defines';
import { SyncSys } from './SyncSys';

import { NRecvCommon } from '../net/recv/NRecvCommon';




const { ccclass, property } = _decorator;

@ccclass('WsSys')
export class WsSys extends SysBase {

    wsCom: WsCom;
    syncSys: SyncSys;


    recvClsMap: Map<number, any> = new Map([
        [Defines.S2C_COMMON, { cls: NRecvCommon }],

    ]); 
    init(token) {
        this.syncSys = SysMgr.getSys(SyncSys);
        this.removeCom(WsCom)
        this.wsCom = this.addCom(WsCom).init(GlobalVar.ws_url + token)
    }

    reConn() {
        if (this.wsCom != null) {
            this.wsCom.reConn()
        }
    }

    close() {
        this.wsCom.close();
    }

    sendMsg(type, api, data) {
        this.wsCom.sendMsg(type, api, data);
    }


    recvData(data: any) {
        this.syncSys.addSyncFunctor(Functor.getFunc(this, "handleData"), data);
    }

    async handleData(data: any) {
        let clsData = this.recvClsMap.get(data.type)
        if (clsData == null) return;

        let func = clsData.cls[data.func]
        if (func == null) return;

        await func(data)
    }
}

